package com.mengdie.shuidi.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.broadcastreceiver.PackageReceiver;
import com.mengdie.shuidi.broadcastreceiver.RemindReceiver;
import com.mengdie.shuidi.broadcastreceiver.URLReceiver;
import com.mengdie.shuidi.event.RobustEvent;
import com.mengdie.shuidi.manager.MDUserMgr;
import com.mengdie.shuidi.model.PushMode;
import com.mengdie.shuidi.ui.activity.BindPhoneActivity;
import com.mengdie.shuidi.ui.activity.MainActivity;
import com.orhanobut.logger.Logger;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageService;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * Created by apple on 17/3/17.
 */

public class MyPushIntentService extends UmengMessageService {
    private static final String TAG = "badger";

    @Override
    public void onMessage(Context context, Intent intent) {
        SharedPreferences countSp = getSharedPreferences("count", Context.MODE_PRIVATE);
        int count = countSp.getInt(TAG, 1);
        try {
            String message = intent.getStringExtra(AgooConstants.MESSAGE_BODY);
            UMessage msg = new UMessage(new JSONObject(message));

            // 对完全自定义消息的处理方式，点击或者忽略
            boolean isClickOrDismissed = true;
            if (isClickOrDismissed) {
                //完全自定义消息的点击统计
                UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
            } else {
                //完全自定义消息的忽略统计
                UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
            }

            //为桌面应用添加角标
            ShortcutBadger.applyCount(MyPushIntentService.this, count);
            count++;
            countSp.edit().putInt(TAG, count).apply();

            Logger.e(msg.custom);
            JSONObject jo = new JSONObject(msg.custom);
            String ret = jo.getString("ret");
            String code = jo.getString("code");
            Logger.e(ret + "  ---" + code);
            if (ret.equals("0")) {
                PushMode pushMode = new Gson().fromJson(msg.custom, PushMode.class);
                PushMode.DataBean data = pushMode.getData();
                if (code.equals("1")) {//跳转网页
                    Intent newIntent = new Intent(this, URLReceiver.class);
                    String url = data.getAndroidUrl();
                    newIntent.putExtra("uri", url);
                    PendingIntent broadcast = PendingIntent.getBroadcast(this, 1, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                    showNotificationBroadCast(broadcast, data, 1);
                } else if (code.equals("2")) {//打开本应用
                    if (MDUserMgr.getInstance().isLogin()) {
                        Logger.e("登陆了" + "-------" + code);
                        openMainActivity(data);
                    } else {
                        Logger.e("没有" + "----" + code);
                        openApp(data);
                    }
                } else if (code.equals("3")) {//打开微信
                    if (MDUserMgr.getInstance().isLogin()) {
                        Logger.e("登陆了" + "-------" + code);
                        openMainActivity(data);
                    } else {
                        Logger.e("没有" + "----" + code);
                        openApp(data);
                    }

                } else if (code.equals("4")) {//打开指定界面
                    openActivity(code, data);

                } else if (code.equals("100")) {//热更新信息
                    EventBus.getDefault().post(new RobustEvent(data));
                } else {
                    if (MDUserMgr.getInstance().isLogin()) {
                        openMainActivity(data);
                    } else {
                        openApp(data);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开指定界面
     *
     * @param code
     * @param data
     */
    private void openActivity(String code, PushMode.DataBean data) {
        if (MDUserMgr.getInstance().isLogin()) {//判断是否登录
            Logger.e("登陆了" + "-------" + code);
            if (data.getActivity().equals("bind_phone")) {
                Logger.e("bind" + "-------" + code);
                Intent newIntent = new Intent(this, BindPhoneActivity.class);
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent activity = PendingIntent.getActivity(this, 4, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                showNotificationBroadCast(activity, data, 4);
            } else if (data.getActivity().equals("three_expire")) {
                // EventBus.getDefault().post(new ExpireRemind(true));
                Logger.e("three_expire" + "-------" + code);
                Intent newIntent = new Intent(this, RemindReceiver.class);
                PendingIntent broadcast = PendingIntent.getBroadcast(this, 5, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                showNotificationBroadCast(broadcast, data, 5);
            }
        } else {
            Logger.e("没有" + "----" + code);
            openApp(data);
        }
    }

    /**
     * 打开 mainActivity
     *
     * @param data
     */
    private void openMainActivity(PushMode.DataBean data) {
        Intent newIntent = new Intent(this, MainActivity.class);
        newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent activity = PendingIntent.getActivity(this, 3, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        showNotificationBroadCast(activity, data, 3);
    }

    /**
     * \
     * 打开 app
     *
     * @param data
     */
    private void openApp(PushMode.DataBean data) {
        Intent newIntent = new Intent(this, PackageReceiver.class);
        newIntent.putExtra("package", "com.mengdie.proxy");
        PendingIntent broadcast = PendingIntent.getBroadcast(this, 2, newIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        showNotificationBroadCast(broadcast, data, 2);
    }

    /**
     * 显示推送通知
     *
     * @param broadcast
     * @param data
     * @param flag  统一设成1 为了只显示一条通知
     */
    private void showNotificationBroadCast(PendingIntent broadcast, PushMode.DataBean data, int flag) {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancelAll();
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle(data.getTitle())
                .setContentText(data.getText())
                .setTicker(data.getTicker())
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.app_logo)
                .setContentIntent(broadcast)
                .setAutoCancel(true);


        Notification notification = builder.getNotification();
        manager.notify(1, notification);

    }
}
